package command;

import java.util.*;

import Exceptions.InsertedRowsException;
import Exceptions.NullPrimaryKeyException;
import Exceptions.TableNotFoundException;
import XMLProcessing.DatabaseProcessing;
import XMLProcessing.TableProcessing;

public class InsertStatement implements IStatement {
	private String table;
	private ArrayList<String> fields;
	private ArrayList<String> values;

	public InsertStatement(String table, ArrayList<String> fields,
			ArrayList<String> values) {
		this.table = table;
		this.fields = fields;
		this.values = values;
	}

	public String toString() {
		String a;
		a = "Insert into " + table + "(";
		for (String t : fields) {
			a += t + ", \n";
		}
		a += ") \n (";

		for (String t : values) {
			a += t + ", \n";
		}
		a += ")";
		return a;
	}

	@Override
	public ResultNode eval() throws TableNotFoundException,
			InsertedRowsException, NullPrimaryKeyException {
		String xmlFile = DatabaseProcessing.retrieveTable(this.table);
		HashMap<String, String> hash = new HashMap<String, String>();
		if (fields.size() != values.size())
			throw new InsertedRowsException();

		for (int i = 0; i < this.fields.size(); i++) {
			hash.put(fields.get(i), values.get(i));
		}
		Boolean a = TableProcessing.insertValues(xmlFile, hash);
		ResultNode rN;

		if (a == true)
			rN = new ResultNode(null, null, 1);
		else
			rN = new ResultNode(null, null, 0);
		return rN;
	}
}
